<template>
  <a-modal
    :dialog-style="{ top: '10px' }"
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <template v-for="s in formData" >
          <a-form-item
            v-if="s.nType == '1'"
            :label="s.name"
            :labelCol="{span: 4}"
            :wrapperCol="{span: 19}"
          >
            <a-input v-decorator="[ `${s.code}`, {rules: [{required: `${s.is_required}` == 'true'? true : false, message: `${s.name}` + '不能为空！'}]}]" />
          </a-form-item>
          <a-form-item
            v-if="s.nType == '6' && type == '0'"
            :label="s.name"
            :labelCol="{span: 4}"
            :wrapperCol="{span: 19}"
          >
            <a-input readonly v-decorator="[ `${s.code}`, {rules: [{required: `${s.is_required}` == 'true'? true : false, message: `${s.name}` + '不能为空！'}]}]" />
          </a-form-item>
          
          <a-form-item
            v-if="s.nType == '5' && type == '1'"
            :label="s.name"
            :labelCol="{span: 4}"
            :wrapperCol="{span: 19}"
          >
            <a-input v-decorator="[ 't'+`${s.code}`, {rules: [{required: `${s.is_required}` == 'true'? true : false, message: `${s.name}` + '不能为空！'}]}]" />
          </a-form-item>
          <a-form-item
            v-if="s.nType == '5' && type == '0'"
            label="部门"
            :labelCol="{span: 4}"
            :wrapperCol="{span: 19}"
          >
            <template >
              <mySelect
                ref="deparment"
                :v-model.sync="deparment"
                @change="deparmentChange"
                v-decorator="['departmentId', {rules: [{required: true, message: '请选择部门！'}]}]"
                  
                :settings="{url:'sysDeparment/getAll', showSearch : true, labelInvalue : false, defaultValue : cuId}"/>
            </template>
          </a-form-item>
          <a-form-item
            v-if="s.nType == '5' && type == '0'"
            :label="s.name"
            :labelCol="{span: 4}"
            :wrapperCol="{span: 19}"
          >
            <person 
              ref="personRef"
              :v-model.sync="personRef"
              @change="personChange"
              :settings="{id:`${s.code}`, departmentId: cuId}"
              v-decorator="[ `${s.code}`, {rules: [{required: `${s.is_required}` == 'true'? true : false, message: `${s.name}` + '不能为空！'}]}]" 
            ></person>
          </a-form-item>
          <a-form-item
            v-show="false" 
            v-if="s.nType == '5' && type == '0'"
            :label="s.name"
            :labelCol="{span: 4}"
            :wrapperCol="{span: 19}"
          >
            <a-input v-decorator="[ 't'+`${s.code}`]" />
          </a-form-item>
          <a-form-item
            v-if="s.nType == '4'"
            :label="s.name"
            :labelCol="{span: 4}"
            :wrapperCol="{span: 19}"
          >
            <mySelect
              :ref="s.code"
              @change="handleSelectChange"
              v-decorator="[`${s.code}`, {rules: [{required: `${s.is_required}` == 'true'? true : false, message: `${s.name}` + '不能为空！'}]}]"
              :settings="{url:'cutDictionaryDetail/getAll',params:{parentId : `${s.dictionary}`}, showSearch : true, allowClear : true,id:`${s.code}`}"/>           
          </a-form-item>
          <a-form-item
            v-show="false" 
            v-if="s.nType == '4'"
            :label="s.name"
            :labelCol="{span: 4}"
            :wrapperCol="{span: 19}"
          >
            <a-input v-decorator="[ 't'+`${s.code}`]" />
          </a-form-item>
          <a-form-item
            v-if="s.nType == '3'"
            :label="s.name"
            :labelCol="{span: 4}"
            :wrapperCol="{span: 19}"
          >
            <a-date-picker 
              v-decorator="[`${s.code}`, {rules: [{required: `${s.is_required}` == 'true'? true : false, message: `${s.name}` + '不能为空！'}]}]"
            />          
          </a-form-item>
          <a-form-item
            v-if="s.nType == '2'"
            :label="s.name"
            :labelCol="{span: 4}"
            :wrapperCol="{span: 19}"
          >
            <a-input-number v-decorator="[ `${s.code}`, {rules: [{required: `${s.is_required}` == 'true'? true : false, message: `${s.name}` + '不能为空！'}]}]" />
          </a-form-item>
        </template>
        <a-form-item
          label="排序"
          :labelCol="{span: 4}"
          :wrapperCol="{span: 19}"
        >
          <a-input-number v-decorator="[ 'sort', {rules: [{required: true, message: '排序不能为空！'}]}]" />
        </a-form-item>
       
      </a-form>
    </a-spin>
  </a-modal>
</template>


<script>
import pick from 'lodash.pick'
  import person from '../../myComponent/Person'

  import {
    postAxiosUrl,
    getUrl
  } from '@/api/manage'
  import mySelect from '../../myComponent/MySelect'
  import moment from 'moment'
  
export default {
  components:{
    mySelect,
	  person
  },
  data () {
    return {
      id : '',
      settingId: '',
      parentId : '',
      checked : false,
      visible: false,
      confirmLoading: false,
      formData : [],
      form: this.$form.createForm(this),
      title : '',
      type : '',
      cuId: '',
      deparment: [],
      cu1: [],
      personRef: [],
    }
  },
  created () {
    
  },
  methods: {
  add (settingId, contentId, type) {
    this.id = 'new'+this.getUUID()
    this.visible = true
    this.type = type
    this.settingId = settingId
    this.parentId = contentId
    this.formData = []
    this.$nextTick(() => {
       this.form.setFieldsValue({ ['sort'] : ''})
    })
  
    this.fetch()
  },
  edit (record, settingId, contentId) {
     this.id = record.id
     this.visible = true
     this.settingId = settingId
     this.parentId = contentId
     this.formData = []
     this.fetch(record)
  },
  callback(key){
    this.activeKey = key
    if(this.activeKey == '2'){
      this.getData(this.id)
    }
  },
  fetch(record) {
    this.loading = true
    var _this = this
    return getUrl('cutSedSettingPerson/getDetail', {settingId : this.settingId})
      .then(data => {debugger
        _this.formData = data.result
        if(record){
          _this.fetchContent(record)
        }
        this.$nextTick(() => {
          if(this.type == '0' && this.id.indexOf('new') > -1){
            if(_this.$refs.deparment)
              _this.getDefaultDepartment()
          }
        })
        
      })
  },
  getData(parentId) {
      var _this = this
       _this.myLoading = true
      getUrl('cutContentPerson/getAll', {contentId : parentId, settingId : this.settingId})
        .then(res => {
           _this.myLoading = false
          _this.data = res.result.data
          _this.columns = res.result.columns
          
         if(_this.columns != ''){
           _this.columns.push({
                title: '操作',
                width : 150,
                fixed: 'right',
                scopedSlots: { customRender: 'action' }
              })
         }
        })
    
  },
  getDefaultDepartment() {
    this.confirmLoading = true
    var _this = this
    return getUrl('cutUser/getDefaultVal', {})
      .then(data => {
        _this.cuId = data.result
        _this.$refs.deparment[0].setValue(data.result)
        _this.confirmLoading = false
      })
  },
  fetchContent(record) {
    this.confirmLoading = true
    var _this = this
    return getUrl('cutContentPerson/getById', {id : record.id})
      .then(data => {
         _this.confirmLoading = false
        
          const { form: { setFieldsValue } } = _this
            _this.type = data.result.cutContent.personType
            _this.$nextTick(() => {
              var red = JSON.parse(data.result.cutContent.data)            
              _this.formData.forEach((item, index) => {
                 if(item.n_type == '4'){
                    setFieldsValue(pick(red, [item.code]))
                    setFieldsValue(pick(red, ['t'+item.code]))
                    _this.$refs[item.code][0].selectModel = red[item.code]
                 }else if(item.n_type == '3'){
                   if(red[item.code] != ''){
                     setFieldsValue({
                       [item.code] : moment(red[item.code], 'YYYY-MM-DD'),
                     })
                   }
                 }else if(item.n_type == '5'){
                   if(_this.type == '1'){
                     setFieldsValue(pick(red, ['t'+item.code]))
                   }else{
                       _this.$refs.personRef[0].setDefault(red[item.code])
                   }
                  
                 }
                 else{
                   setFieldsValue(pick(red, [item.code]))
                 }
              })
               setFieldsValue(pick(red, ['sort']))
          })
      })
  },
  handleSelectChange(v1, v2, id){
      var text = v2.componentOptions.children[0].text
      this.form.setFieldsValue({
        ['t'+id] : text,
      })
  },
  close () {
      this.$emit('close')
      this.visible = false
  },
  handleCancel () {
      this.close()
  },
  processData(values){
    var data = []
    var jsonStr = ''
    var jsonData = {}
    this.formData.forEach((item, index) => {
      if(item.n_type == '4'){
        jsonData[item.code] = values[item.code]
         jsonData['t'+item.code] = values['t'+item.code]
      }else if(item.n_type == '3'){
        var value = values[item.code]
        if(value != null && value != '' && value != undefined){
          value = value.format('YYYY-MM-DD')
        }else{
           value = ''
        }
        jsonData[item.code] =value
      }else if(item.n_type == '5'){
        if(this.type == '1'){
          jsonData[item.code] = 'otherPeerson'
        }else{
           jsonData[item.code] = values[item.code]
        }
         jsonData['t'+item.code] = values['t'+item.code]
      }else{
        jsonData[item.code] = values[item.code]
      }
    })
    jsonData['sort'] = values['sort']
    return JSON.stringify(jsonData )
  },
  handleOk () {
      const _this = this
      
      // 触发表单验证
      this.form.validateFields((err, values) => {
        // 验证表单没错误
        if (!err) {
          console.log('form values', values)
          _this.confirmLoading = true
         values.id = this.id
         values.contentId = this.parentId
         values.settingId = this.settingId
         values.personType = this.type
         values.data = _this.processData(values)
         postAxiosUrl('cutContentPerson/save', values)
           .then(data => {
              if(!data.success){
                 _this.$message.warning(data.error)
                 _this.confirmLoading = false
               }else{
                 _this.visible = false
                 _this.confirmLoading = false
                 _this.$emit('ok', values)
               }           
             })
        }
      })
    },
    handleAddPerson(){
      
    },
    deparmentChange(v1, v2){
      this.cuId  = v1
      var id = this.$refs.personRef[0].$el.id
        this.$refs.personRef[0].clear()
        this.form.setFieldsValue({
          '02': '',
        })
        this.form.setFieldsValue({
          [id] : '',
        })
    },
    personChange(v1, v2, id){
      var title = ''
      switch(v2.title) {
           case '1': title = '教授'; break
           case '2': title = '副教授'; break
           case '3': title = '讲师'; break
           case '4': title = '研究员'; break
           case '5': title = '副研究员'; break
           default: title = ''
      } 
      
      this.form.setFieldsValue({
        '02': title,
      })
      this.form.setFieldsValue({
        [id] : v1,
      })
     this.form.setFieldsValue({
       ['t'+id] : v2.name,
     })
     if(v2.dId){
       this.$refs.deparment[0].setDefault(v2.dId)
       this.form.setFieldsValue({
          ['departmentId'] : v2.dId,
        })
     }
    }
  }
}
</script>

<style>
  .ant-input-number{
    width: 100%;
  }
</style>
